import redis
import traceback
import json
from utils.log import MyLog


class Config:
    # mysql连接
    redis_host = '127.0.0.1'
    redis_port = 6727
    decode_responses = True
    redis_extime = 604800

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)


class RedisHandler():
    def __init__(self, config):
        self.log = MyLog(config.log_dir, __name__).getlog()
        self.host = config.redis_host
        self.port = config.redis_port
        self.dr = config.decode_responses
        self.pool = redis.ConnectionPool(host=self.host, port=self.port, decode_responses=self.dr)
        self.red = redis.StrictRedis(connection_pool=self.pool)
        try:
            self.tiezi_pool = redis.ConnectionPool(host='rm32199.eos.grid.sina.com.cn', port=32199, db=0)
            self.circle_red = redis.StrictRedis(connection_pool=self.tiezi_pool)
            self.sums_tiezi = self.circle_red.zcard("sina_hot_search")

        except Exception as e:
            self.log.exception(e)

        # 失效时间
        self.last_time = config.redis_extime

    def count_tiezi(self, group_id):
        sums_tiezi_in_circle = 0
        try:
            sums_tiezi_in_circle = len(
                self.circle_red.zscan("sina_hot_search", match=f'*"circle_id": "{group_id}"*',
                                      count=self.sums_tiezi)[-1])
        except Exception as e:
            self.log.exception(e)
        return sums_tiezi_in_circle

    def add(self,group_id,sample,extime=0):
        if extime == 0:extime =self.last_time
        str_sample = json.dumps(sample,ensure_ascii=False)
        #str_sample = json.dumps(sample,ensure_ascii=False)
        try:
            self.red.set(str(group_id),str_sample,ex=extime)
            # self.log.info('query:'+str(group_id)+'\t'+'recall:'+str_sample)
            return True
        except Exception as e:
            self.log.exception(e)

    def existed(self,group_id):
        if not group_id: return {}
        result = self.red.get(str(group_id))
        if result:
            return json.loads(result)
        else:
            return {}


    def redis_clear(self):
        self.red.flushdb()

    def redis_count(self):
        return self.red.dbsize()


if __name__ == '__main__':
    opt = Config()
    red = RedisHandler(opt)
    # red.redis_clear()
    print(red.redis_count())
    print(red.red.keys())

